<?php
/**
 * Service of Customer
 *
 * @author fsqijy
 */

require_once BaseUtil::getModulePath("dbgrid")  .  '/DBGrid.php';
require_once BaseUtil::getModulePath("dbgrid")  .  '/DBGridConstant.php';
require_once BaseUtil::getModulePath("base")  .  '/services/BaseService.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/CustomerDao.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/CommentDao.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/CommentReplyDao.php';
require_once BaseUtil::getModulePath ( "component" ) . '/Number.php';
require_once BaseUtil::getModulePath("common")  .  '/models/CampusesDao.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/AccountAgentTotalsDao.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/AgentCertificatesDao.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/CustomerWishlistDao.php';
require_once BaseUtil::getModulePath("systemlog")  .  '/services/SystemLogService.php';

class CustomerService extends BaseService {

    private $customerDao;
    /**
     * CommentDao
     */
    private $commentDao;
    private $commentReplyDao;
    private $campusDao;
    private $accountAgentTotalsDao;
    private $agentCertificateDao;
    private $customerWishlistDao;

    public function __construct ()
	{
		parent::__construct();
		$this->customerDao = new CustomerDao();
		$this->customerDao->setDb($this->db);
        $this->commentDao = new CommentDao();
        $this->commentDao->setDb($this->db);
        $this->commentReplyDao = new CommentReplyDao();
        $this->commentReplyDao->setDb($this->db);
        
        $this->campusDao = new CampusesDao();
        $this->campusDao->setDb($this->db);
        
        $this->accountAgentTotalsDao = new AccountAgentTotalsDao();
        $this->accountAgentTotalsDao->setDb($this->db);
        $this->agentCertificateDao = new AgentCertificatesDao();
        $this->agentCertificateDao->setDb($this->db);
        
        $this->customerWishlistDao = new CustomerWishlistDao();
        $this->customerWishlistDao->setDb($this->db);
	}

    public function getCustomers($view, $form , $isAjax = false){
        $status = array("0"=>$this->_translate->translate("unactivated"),"1"=>$this->_translate->translate("active"),"2"=>$this->_translate->translate("suspend"));
		$userType = array("1"=>$this->_translate->translate("certf1"),"3"=>$this->_translate->translate("certf3"),"4"=>$this->_translate->translate("certf4"),
		 "5"=>$this->_translate->translate("certf5"),"6"=>$this->_translate->translate("certf6"));
        
		$campuses = $this->campusDao->getAllCampuses();
		foreach($campuses as $campus){
			$campusArr[$campus['id']] = $campus['area_name'];
		}
		
		$dbGrid = new DBGrid($view);
		$dbGrid->setPost($form);
        $dbGrid->setModule("/customer/customer");
        $dbGrid->addValueFilter("is_delete",0);
       
        $dbGrid->addSelectOptionFilter("id", $this->_translate->translate("id"),DBGridConstant::OPERATOR_EQUAL);
        $dbGrid->addSelectOptionFilter("name", $this->_translate->translate("name"));
        $dbGrid->addSelectOptionFilter("full_name", $this->_translate->translate("fullName"));
        $dbGrid->addSelectOptionFilter("email", $this->_translate->translate("email"));
    
        $dbGrid->addAdvanceFilter(DBGridConstant::FILTER_TYPE_TEXT, "name",$this->_translate->translate("name"));
        $dbGrid->addAdvanceFilter(DBGridConstant::FILTER_TYPE_TEXT, "full_name",$this->_translate->translate("fullName"));
        $dbGrid->addAdvanceFilter(DBGridConstant::FILTER_TYPE_TEXT, "email",$this->_translate->translate("email"));
        $dbGrid->addAdvanceOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "certf",$this->_translate->translate("userType"),$userType);
      
      
        $dbGrid->addAdvanceOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "status",$this->_translate->translate("status"), $status);
     
        $dbGrid->addAdvanceOptionsFilter(DBGridConstant::FILTER_TYPE_SELECT, "campus_id",$this->_translate->translate("belongHighSchool"), $campusArr);
      
        $dbGrid->addFetchTable("users", "*");
        $dbGrid->addFetchColumn("id", $this->_translate->translate("id"),"edit",array(),"",DBGridConstant::CALL_SELF_METHOD,"Customer.openEditDialog");
              
        $dbGrid->addFetchColumn("name", $this->_translate->translate("name"));
        $dbGrid->addFetchColumn("full_name", $this->_translate->translate("fullName"));
        $dbGrid->addFetchColumn("email", $this->_translate->translate("email"));
        $dbGrid->addFetchColumn("certf", $this->_translate->translate("userType"),"",$userType);
        $dbGrid->addFetchColumn("status", $this->_translate->translate("status"),"",$status);
        $dbGrid->addFetchColumn("campus_id", $this->_translate->translate("belongHighSchool"),"",$campusArr);
        $dbGrid->addFetchColumn("last_login", $this->_translate->translate("lastLogin"));
    
        //module action
        $dbGrid->addAAModuleAction("customer","edit",$this->_translate->translate("editBtn"),"edit");
        $dbGrid->addAAModuleAction("customer","delete",$this->_translate->translate("delBtn"),"deletesome");
        $dbGrid->addAAModuleAction("customer","add",$this->_translate->translate("addBtn"),"add",array(),DBGridConstant::CALL_SELF_METHOD,"Customer.openAddDialog");
        $dbGrid->setPageTitle($this->_translate->translate("customerManage"));
       // $dbGrid->isExport(true);
        if($isAjax){
            return $dbGrid->renderByAjax();
        }else{
            return $dbGrid->render();
        }
    }

    public function addCustomer($form){
        $customer = array();
        $customer["name"] = $form->getValue("name");
        $customer["email"] = $form->getValue("email");
        $customer["password"] = md5($form->getValue("password"));
        $customer['status'] = 1;
        $customer['user_num'] = Number::getCustomerNumber();
        $userType = $form->getValue("userType");
        $customer['certf'] = $userType;
        if($userType==3 || $userType==5){
        	$customer['team_name'] = $form->getValue("teamName");
        	$customer['full_name'] = $form->getValue("fullName");
        	$customer['addr'] = $form->getValue("receiveAddr");
        	$customer['district'] = $form->getValue("province");
        	$customer['city'] = $form->getValue("city");
        	$customer['mobile'] = $form->getValue("mobile");
        	$customer['phone'] = $form->getValue("phone");
        	$customer['postal_code'] = $form->getValue("zipCode");
        } 
        $this->customerDao->insertData($customer);
    }

    public function editCustomer($form){
        $customer = array();
        $userId = $form->getValue("id");
        $totalBuyerPoint = $form->getValue("pointsBuyerTotal");
        $customer["name"] = $form->getValue("name");
        $customer["email"] = $form->getValue("email");
        if($form->getValue("password") != ""){
             $customer["password"] = md5($form->getValue("password"));
        }
        $customer['status'] = $form->getValue("status");
        $userType = $form->getValue("userType");
        if(empty($userType)){
           $userType = 3;
        }
        if($userType == 3){
        	$customer['parent_id'] = 0;
        	$userAccountAgent = $this->accountAgentTotalsDao->getByUserID($userId);
        	$data = array("user_id" => $userId);
        	if(empty($userAccountAgent)){
        		$this->accountAgentTotalsDao->insertData($data,true);
        	}
        	$agentCertificate = $this->agentCertificateDao->getByUserID($userId);
        	if(empty($agentCertificate)){
        		$this->agentCertificateDao->insertData($data,true);
        	}
        }
        
        $customer['certf'] = $userType;
        $customer['campus_id'] = trim($_POST['campusesID']);
       
        $customer['points_buyer'] = $form->getValue("pointsBuyer");
     //   $customer['points_seller'] = $form->getValue("pointsSeller");
        $customer['points_buyer_total'] = $totalBuyerPoint;
      //  $customer['points_seller_total'] = $form->getValue("pointsSellerTotal");
       
        $customer['rank'] = self::getRankByPoint($totalBuyerPoint);
        if($userType==3 || $userType==5 || $userType==4){
        	$customer['team_name'] = $form->getValue("teamName");
        	$customer['full_name'] = $form->getValue("fullName");
        	$customer['addr'] = $form->getValue("receiveAddr");
        	$customer['district'] = $form->getValue("province");
        	$customer['city'] = $form->getValue("city");
        	$customer['mobile'] = $form->getValue("mobile");
        	$customer['phone'] = $form->getValue("phone");
        	$customer['postal_code'] = $form->getValue("zipCode");
        } else if($userType==1 || $userType==6 || $userType==7) {
        	/*$customer['team_name'] = "";
        	$customer['full_name'] = "";
        	$customer['addr'] = "";
        	$customer['district'] = "";
        	$customer['city'] = "";
        	$customer['mobile'] = "";
        	$customer['phone'] = "";
        	$customer['postal_code'] = "";*/
        }
        
        $this->customerDao->updateCustomer($customer, $userId);
        //insert log
        $log=new SystemLogService();
        $loginUser = BaseUtil::getLoginUser();
        $log->insertSystemLog('EDITUSER',$loginUser['uname'], $customer,$userId);        
    }

    public function getCustomerById($id){
       return $this->customerDao->getByCol("id",$id);
    }

    public function getCustomerByName($name){
       return $this->customerDao->getByCol("name",$name);
    }
    
    public function deleteCustomers($ids){
		foreach($ids as $id){
            if(!empty($id)){
                $this->customerDao->deleteCustomer($id);
            }
        }
    }
    
    public function delete($ids) {
    	if(!empty($ids)) {
    		$this->customerDao->deleteCustomer($ids);
    	}
    }

    public function getLastCustomerByLimit($limit){
        return $this->customerDao->getCustomerByLimit(10);
    }
    
/**
 * Steve
 */
    public function checkUserByName($name,$id){
    	return $this->customerDao->checkUserByName($name,$id);
    }
    public function checkUserByEmail($email,$id){
    	return $this->customerDao->checkUserByEmail($email,$id);
    }
/**
 * Check that if all agency relations is relieved for usertype change
 */    
    public function getUsersByPId($parentId){
    	return $this->customerDao->getUsersByPId($parentId);
    }

    public function getUserCommentsList($view, $form, $isAjax=false){
          $dbGrid = new DBGrid($view);
          $dbGrid->setPost($form);
          $dbGrid->setModule("/customer/customer");
          $dbGrid->addValueFilter("c-is_delete",0);
          $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT,"c-id", $this->_translate->translate("id"),DBGridConstant::OPERATOR_EQUAL);
          $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT,"p-title", $this->_translate->translate("productTitle"));
          $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT,"u-name", $this->_translate->translate("name"));
          $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT,"c-point", $this->_translate->translate("point"));
          $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT,"c-content", $this->_translate->translate("content"));
          
          $dbGrid->addDateFilter("c-created", $this->_translate->translate("createDate"));
          $dbGrid->addFetchTable("comments as c", "c.*");
          $dbGrid->addFetchTable('users as u','u.name', 'c.user_id=u.id', DBGridConstant::JOIN_TYPE_INNER);
          $dbGrid->addFetchTable('comment_replies as r', "if(r.id>0,'Y','N') as isreplied",'c.id=r.comment_id', DBGridConstant::JOIN_TYPE_OUTER);
          $dbGrid->addFetchTable('products as p', 'p.title', 'c.product_id = p.id', DBGridConstant::JOIN_TYPE_INNER);
          $dbGrid->addFetchColumn("id", $this->_translate->translate("id"),"editcomments");
          $dbGrid->addFetchColumn("title", $this->_translate->translate("productTitle"));        
          $dbGrid->addFetchColumn("name", $this->_translate->translate("name")); 
          $dbGrid->addFetchColumn("point", $this->_translate->translate("point"));        
          $dbGrid->addFetchColumn("content", $this->_translate->translate("content"));
          $dbGrid->addFetchColumn("isreplied", $this->_translate->translate("isreplied"),"",array("Y"=>$this->_translate->translate("yesLabel"),"N"=>$this->_translate->translate("noLabel")));
          $dbGrid->addFetchColumn("created", $this->_translate->translate("createDate"));
          
          if(AAService::isAllowed("customer", "addcomment")) {
              $dbGrid->addModuleAction("add",$this->_translate->translate("addBtn"),"addcomment");
          }
          $dbGrid->setSortOrder("c-created");
          $dbGrid->setPageTitle($this->_translate->translate("CommentsManage"));
          return $dbGrid->render();
    }
    
    public function getCommentById($id){
    	return $this->commentDao->getCommentById($id);
    }
    
    public function saveCommentReply($param){
    	return $this->commentReplyDao->saveReply($param);
    }
    
    public function deleteComment($commentId){
    	$this->commentDao->deleteCommentById($commentId);
    }
    
    public function addComment($form)
    {
        $offset=rand(20,40);
        $comment = array();
        $comment["user_id"] = $form->getValue("userId");
        $comment["point"] = $form->getValue("point");
        $comment["product_id"] = $form->getValue("productId");
        $comment["content"] = $form->getValue("commentText");
        $comment["show_in_product"] = $form->getValue("showInProduct");
        $comment["created"] = date("Y-m-d H:i:s",strtotime("-$offset minutes"));
        $comment["modified"] = date("Y-m-d H:i:s",strtotime("-$offset minutes"));
        
        $id = $this->commentDao->insert($comment);
        
        $commentReply = array();
        $commentReply["comment_id"] = $id;
        $admin = BaseUtil::getLoginUser();
        $adminId = $user['uid'];
        $commentReply["reply_id"] = $adminId; 
        $commentReply["content"] = $form->getValue("replyText");
        $id = $this->commentReplyDao->insert($commentReply);
    }
    
    public function returnPoints($points,$userID){
    	$this->customerDao->returnPoints($points,$userID);
    }
    
    public function searchCustomer($view, $post ,$from){
        $dbGrid = new DBGrid($view);
        $dbGrid->setPost($post);
        $dbGrid->setFilterAction(HttpUtil::baseUrl() . "/customer/customer/searchcustomer/from/" . $from);
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "users-user_num", $this->_translate->translate("customerNo"));
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "users-name", $this->_translate->translate("name"));
        $dbGrid->addFilter(DBGridConstant::FILTER_TYPE_TEXT, "users-email", $this->_translate->translate("email"));
        
        $dbGrid->addFetchTable("users", "*");
        $dbGrid->addValueFilter("users-status", "1");
        $dbGrid->addValueFilter("users-is_delete", "0");
        $dbGrid->addFetchColumn("id", $this->_translate->translate("id"));
        $dbGrid->addFetchColumn("user_num", $this->_translate->translate("customerNo"));
        $dbGrid->addFetchColumn("name", $this->_translate->translate("name"));
        $dbGrid->addFetchColumn("email", $this->_translate->translate("email"));
       
        /*$dbGrid->addFetchHiddenColumn("attribute_1");
        $dbGrid->addFetchHiddenColumn("value_1");
        $dbGrid->addFetchHiddenColumn("attribute_2");
        $dbGrid->addFetchHiddenColumn("value_2");
        $dbGrid->addFetchHiddenColumn("attribute_3");
        $dbGrid->addFetchHiddenColumn("value_3");
        $dbGrid->addFetchHiddenColumn("attribute_4");
        $dbGrid->addFetchHiddenColumn("value_4");
        $dbGrid->addFetchHiddenColumn("attribute_5");
        $dbGrid->addFetchHiddenColumn("value_5");*/
        $dbGrid->setPageTitle($this->_translate->translate("searchCustomer"));
        $dbGrid->setModule('/customer/customer');
        $dbGrid->setReturnData(true);
        if($from == "promotion"){
           $dbGrid->setCallBackMethod("Promotion.searchCustomer");
        }    
        if($from == "email"){  
           $dbGrid->setCallBackMethod("Email.searchCustomer");
        }
        return $dbGrid->renderAjaxDbGrid();
    }
    public static function getRankByPoint($point){
        if($point < 1000){
        	$rank = 1;
        } else if($point < 4000){
        	$rank = 2;
        } else if($point < 10000){
        	$rank = 3;
        } else if($point < 25000){
        	$rank = 4;
        } else if($point < 50000){
        	$rank = 5;
        } else {
        	$rank = 6;
        }
        
        return $rank;
    }
    
    public function getCustomersByCertf($certfStr){
    	return $this->customerDao->getCustomersByCertf($certfStr);
    }
    
    public function getCustomersByRank($rankStr){
    	return $this->customerDao->getCustomersByRank($rankStr);
    }

/*
 *  Customer Wishlists
 */
    public function getWishlistByCustomerId($customerId,$offset=0,$limit=0){
    	return $this->customerWishlistDao->getWishlistByCustomerId($customerId,$offset,$limit);
    }
    
    public function getWishListTotalNum($customerId){
    	return $this->customerWishlistDao->getWishListTotalNum($customerId);
    }
    
    // get an invalid user randomly
    public function getRandomInvalidUser()
    {
        return $this->customerDao->getRandomInvalidUser();
    }
}